package com.slipper.scheduled;

import com.slipper.PaasContext;
import com.slipper.collect.CollectTask;
import com.slipper.exception.CommonException;
import com.slipper.system.collect.bo.CollectTableBO;
import com.slipper.system.collect.bo.CollectTaskBO;
import com.slipper.system.collect.service.CollectColumnService;
import com.slipper.system.collect.service.CollectTableService;
import com.slipper.system.collect.service.CollectTaskService;
import com.slipper.system.schedule.bo.ScheduleBO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class CollectRunnable implements IScheduledRunnable {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public boolean supports(ScheduleBO schedule) {
        return ScheduleBO.BUSINESS_COLLECT.equals(schedule.getBusinessType());
    }

    @Override
    public Runnable createRunnable(ScheduleBO schedule) {
        return () -> {
            try {
                CollectTableBO qo = new CollectTableBO();
                qo.setTaskId(schedule.getBusinessId());
                List<CollectTableBO> tableList = PaasContext.getBean(CollectTableService.class).queryList(qo);

                CollectTaskBO task = PaasContext.getBean(CollectTaskService.class).queryBy(schedule.getBusinessId());
                task.setTableList(tableList);
                PaasContext.getBean(CollectColumnService.class).fillColumn(task.getTableList());
                Thread thread = new Thread(new CollectTask(task));
                thread.start();
                thread.join();
            } catch (Exception e) {
                logger.error("执行定时任务失败！", e);
                throw new CommonException("执行定时任务失败, " + e.getMessage(), e);
            }
        };
    }
}